﻿/*
 * Created by SharpDevelop.
 * User: it1050
 * Date: 29/03/11
 * Time: 21:24
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using org.pdfbox.util;
using org.pdfbox.pdmodel;

namespace MailInvoice
{
  /// <summary>
  /// Description of MainForm.
  /// </summary>
  public partial class MainForm : Form
  {
    string vTargetPath;//path per la cartella temporanea in cui copiare i file ed eseguire i job
    
    public MainForm()
    {
      //
      // The InitializeComponent() call is required for Windows Forms designer support.
      //
      InitializeComponent();
            
    } //MainForm()
//-------------------------------------------------------------------------------------------------------//    
    void fSplitFile(string pFname)
    {
      //
      // prendo il file pdf e lo decomprimo suddividendolo in singole pagine
      //
      //string vTargetPath;  //path per la cartella temporanea in cui copiare i file ed eseguire i job
      
      string vOutFname="";    //fileName in output x splitting
      string vTxtRead="";     //estrazione dati in formato testo dal PDF
      string vOutFRename="";  //fileName in output
      string[] vFileArr=new string[50];//array stringa per la ricompattazione del file
      string vKeyMerge="";    //var di controllo per verificare il cambio del documento
      int vKeySrcIdx=0;       //indice per ricerca substring codice cliente-fattura
      int vPagesIdx=0;        //indice per l'array delle pagine
        
      if (pFname=="")
        MessageBox.Show("PDF File Missed!");
      
      //build temp path
      
      vTargetPath=Path.GetDirectoryName(Application.ExecutablePath)+"\\temp\\";
      edtLog.Text+=DateTime.Now.ToString()+"-- Checking temp dir... "+ vTargetPath+" \r\n";
      if (!System.IO.Directory.Exists(vTargetPath))
      {
        edtLog.Text+=DateTime.Now.ToString()+"-- Folder not found... Creating"+" \r\n"; 
        System.IO.Directory.CreateDirectory(vTargetPath);
      }
      
      // Open the file
      PdfDocument inputDocument = PdfReader.Open(pFname, PdfDocumentOpenMode.Import);
      Application.DoEvents();
      edtLog.Text+=DateTime.Now.ToString()+"-- Open PDF File " + pFname+" \r\n"; 

      string vName = Path.GetFileNameWithoutExtension(pFname);
      for (int idx = 0; idx <= inputDocument.PageCount; idx++)
      {
        //quando sono all'ultima pagina devo cmq compattare l'ultimo file
        if (idx == inputDocument.PageCount) 
        {
          //richiamo la creazione del file che ragrruppa la singola fattura
          fMakeSingle(vFileArr, vTargetPath+vKeyMerge, true);
        }
        else
        {
          // Create new document
          edtLog.Text+=DateTime.Now.ToString()+String.Format("-- Processing page {0}",idx + 1)+" \r\n";
          PdfDocument outputDocument = new PdfDocument();
          outputDocument.Version = inputDocument.Version;
          outputDocument.Info.Title = String.Format("Page {0} of {1}", idx + 1, inputDocument.Info.Title);
          outputDocument.Info.Creator = inputDocument.Info.Creator;
  
          // Add the page and save it
          outputDocument.AddPage(inputDocument.Pages[idx]);
          vOutFname = String.Format(vTargetPath+"{0}-Page-{1:000}.pdf", vName, idx + 1);
          outputDocument.Save(vOutFname);
          Application.DoEvents();
          
          // leggo il contenuto del file
          vTxtRead=fReadFile(vOutFname);
          // cerco all'interno della stringa il substring "xk" che delimita l'inizio 
          //   del codice utente e nr fattura
          vKeySrcIdx=vTxtRead.IndexOf(@"xk");
          if (vKeySrcIdx!=-1) //Rinomino il file 
          {
            vOutFRename=vTargetPath+String.Format(vTxtRead.Substring(vKeySrcIdx+3,15)+"-{0:000}.pdf", idx + 1);
            if (File.Exists(vOutFRename)) File.Delete(vOutFRename);
            File.Move(vOutFname, vOutFRename);
            //verifico se si stia cmabiando documento e si debbano quindi compattare i file pdf generati sinora
            if (idx != 0 && vTxtRead.Substring(vKeySrcIdx+3,15) != vKeyMerge) 
            {
              //richiamo la creazione del file che ragrruppa la singola fattura
              fMakeSingle(vFileArr, vTargetPath+vKeyMerge, true);
              
              //reinizializzo l'array
              Array.Clear(vFileArr,0,vFileArr.Length);
              //reinizializzo il contatore per le pagine
              vPagesIdx=0;
              
              // TODO : prevedere la parte per l'invio tramite mail
            }
              
            //aggiungo all'array il documento successivo
            vFileArr[vPagesIdx] = vOutFRename;
            
            vKeyMerge = vTxtRead.Substring(vKeySrcIdx+3,15); //imposto il valore x il controllo 
            vPagesIdx++; //aggiorno il contatore per le pagine
          }
          else
            MessageBox.Show("Error customer & Invoice key not found!", "ERROR");
        }  
      } // for sullo split dei file
      
    } // SplitFile()
//-------------------------------------------------------------------------------------------------------//    
    string fReadFile(string pFname)
    {
      //
      // leggo il file pdf e ne estraggo il contenuto di testo ritornandolo come risultato della funzione
      //
      string vResult="";
      string strExtension = pFname.Substring(pFname.LastIndexOf(".") + 1);
      //Validate filetype
      if (strExtension.ToUpper() != "PDF")
        MessageBox.Show( "Please select a PDF file");
      else
      {
        //User interface status updates
        Cursor = Cursors.WaitCursor;
        edtLog.Text += "Extracting text...please wait..."+" \r\n";
        Application.DoEvents();
        try
        {
          //Extract text from PDF file
          PDDocument objDocument = PDDocument.load(pFname);
          Application.DoEvents();
          PDFTextStripper objTextStripper = new PDFTextStripper();
          vResult = objTextStripper.getText(objDocument);
        }
        catch (Exception ex)
        {
          vResult = "Exception: " + ex.Message;
        }
        //Restore cursor
        Cursor = Cursors.Default;
      }
      return vResult;  
    } // fReadFile
//-------------------------------------------------------------------------------------------------------//    
    void fMakeSingle(string[] pFilesArr, string pOutFname, bool pDeleteOrigFiles)
    {
      //
      // ciclo sui file passati come parametro in array e creo un file nominato dal nr fattura 
      //   ed elimino i file di origine
      //
      
      // Open the output document
      PdfDocument outputDocument = new PdfDocument();
      
      // Iterate files
      foreach (string file in pFilesArr)
      {
        //chk if string is not empty
        if (file!=null)
          {
          // Open the document to import pages from it.
          PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import);
          
          // Iterate pages
          int count = inputDocument.PageCount;
          for (int idx = 0; idx < count; idx++)
          {
            // Get the page from the external document...
            PdfPage page = inputDocument.Pages[idx];
            // ...and add it to the output document.
            outputDocument.AddPage(page);
          }
          //delete original file
          if (pDeleteOrigFiles)
            File.Delete(file);
        }
      }
      // Save the document...
      outputDocument.Save(pOutFname+".pdf");
      
    } // fMakeInvoiceFile
//-------------------------------------------------------------------------------------------------------//
    void fProcessSplittedFiles()
    {
      //recupero l'elenco completo dei file della cartella temp
      string[] filePaths = Directory.GetFiles(vTargetPath);

      
      foreach (string filePath in filePaths)
        File.Delete(filePath);
    }
//-------------------------------------------------------------------------------------------------------//
    void BtnOpenFileClick(object sender, EventArgs e)
    {
      dlgOpenFile.Title="select file";
    	if (dlgOpenFile.ShowDialog() == DialogResult.OK)
    	  edtPDFFile.Text = dlgOpenFile.FileName.ToString();
    } // BtnOpenFileClick
//-------------------------------------------------------------------------------------------------------//    
    void BtnRunClick(object sender, EventArgs e)
    {
      //pulisco il log
      edtLog.Text="";
      
    	//Splitto il pdf in pagine singole nella subdir temp
    	fSplitFile(edtPDFFile.Text);
    	
//    	MessageBox.Show(fReadFile(edtPDFFile.Text));
    	MessageBox.Show("Done");
    } // BtnRunClick
//-------------------------------------------------------------------------------------------------------//    

  } // class MainForm : Form
}
